#pragma once
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>
#include <functional>
#include <ctime>
#include <queue>
#include <stdarg.h>
#include <sys/types.h>
#include "Task.hpp"

using namespace std;

class ThreadData
{
public:
    ThreadData(const string name)
        :threadname(name)   
    {}
    ~ThreadData()
    {}
public:
    string threadname;
};

const int default_value = 5;

template <class T>
class ThreadPool
{
private:
    ThreadPool(int thread_num = default_value)
        :_thread_num(thread_num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);

        for(int i = 0; i < _thread_num; i++)
        {
            string threadname = "thread-";
            threadname += to_string(i+1);

            ThreadData td(threadname);
            // Thread<ThreadData> t(threadname, bind(&ThreadPool<T>::ThreadRun, this, placeholders::_1), td);
            
            _threads.emplace_back(threadname, bind(&ThreadPool<T>::ThreadRun, this, placeholders::_1), td);
        }
    }

    ThreadPool(const ThreadPool<T> &tp) = delete;
    const ThreadPool<T> &operator=(const ThreadPool<T>) = delete;
public:
    static ThreadPool<T> *GetInstance()
    {
        if(instance == nullptr)
        {
            LockGuard lockguard(&sig_lock);
            if(instance == nullptr)
            {
                lg.LogMessage(Info, "创建单例成功 ...\n");
                instance = new ThreadPool<T>();
            }
        }
        return instance;
    }
    // ThreadPool(int thread_num = default_value)
    //     :_thread_num(thread_num)
    // {
    //     pthread_mutex_init(&_mutex, nullptr);
    //     pthread_cond_init(&_cond, nullptr);

    //     for(int i = 0; i < _thread_num; i++)
    //     {
    //         string threadname = "thread-";
    //         threadname += to_string(i+1);

    //         ThreadData td(threadname);
    //         // Thread<ThreadData> t(threadname, bind(&ThreadPool<T>::ThreadRun, this, placeholders::_1), td);
            
    //         _threads.emplace_back(threadname, bind(&ThreadPool<T>::ThreadRun, this, placeholders::_1), td);
    //     }
    // }

    bool Start()
    {
        for(auto &thread : _threads)
        {
            thread.Start();
            lg.LogMessage(Info, "%s is running ...\n", thread.ThreadName().c_str());
        }
        return true;
    }

    void Threadwait(const ThreadData &td)
    {
        lg.LogMessage(Debug, "no task, %s is sleeping ...\n", td.threadname.c_str());
        pthread_cond_wait(&_cond, &_mutex);
    }

    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void ThreadRun(ThreadData &td)
    {
        while(true)
        {
            // 取任务
            T t;
            {
                pthread_mutex_lock(&_mutex);
                while(_q.empty())
                {
                    Threadwait(td);
                    lg.LogMessage(Debug, "have task, %s is wakeup ...\n", td.threadname.c_str());
                }
                t = _q.front();
                _q.pop();

                pthread_mutex_unlock(&_mutex);
                sleep(1);
            }
            // 处理任务
            t.Run();
            lg.LogMessage(Debug, "%s handler task %s done, result is : %s\n",td.threadname.c_str(), t.PrintTask().c_str(), t.PrintResult().c_str());
        }
    }

    void Push(T &in)
    {
        lg.LogMessage(Debug, "other thread push a task is : %s\n", in.PrintTask().c_str());
        LockGuard lockguard(&_mutex);
        _q.push(in);
        ThreadWakeup();
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    // for test
    void Wait()
    {
        for(auto &thread : _threads)
        {
            thread.Join();
        }
    }
private:
    queue<T> _q;
    vector<Thread<ThreadData>> _threads;
    int _thread_num;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T> *instance;
    static pthread_mutex_t sig_lock;
};

template<class T>
ThreadPool<T> *ThreadPool<T>::instance = nullptr;
template<class T>
pthread_mutex_t ThreadPool<T>::sig_lock = PTHREAD_MUTEX_INITIALIZER;